#include "DxConsoleSampleScene.h"

#include "DxConsoleSampleNode.h"
#include "DXConsole/Console.h"
#ifdef _DEBUG
#pragma comment(lib,"DXConsole_Debug.lib");
#else
#pragma comment(lib,"DXConsole_Release.lib");
#endif
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

};


	
#pragma comment(lib,"lua5.1.lib");
#pragma comment(lib,"lua51.lib");
 lua_State *L;
 


int ConsoleCallbackEnter (const char* str)
{
	//MessageBoxA(NULL,str,str,0);

		//    freopen("CONOUT$","w",stdout); 
	if (luaL_loadbuffer(L, str,strlen(str),"sd")  ==0) // load and run the file
		
		{
			lua_pcall(L,0,0,0);
		  int s =lua_gettop(L);
		   const	char * pStr=lua_tostring(L,-1) ;
			if(pStr)
	       	DXConsoleStdout(pStr   );
			 
	}
	 
	else
		printf("unable to load Example.lua \n" );

	


	return 0;
}
CDxConsoleSampleNode::CDxConsoleSampleNode(void):ISceneNode(Singleton<CDxConsoleSampleScene>::Instance())
{
}


CDxConsoleSampleNode::~CDxConsoleSampleNode(void)
{
}

void CDxConsoleSampleNode::OnUpdate( double fTime, float fElapsedTime )
{
	if(Singleton<CInput>::Instance()->GetKeyboard()->IsKeyPressed(DIK_C)  &&Singleton<CInput>::Instance()->GetKeyboard()->IsKeyPressed(DIK_LALT)  )
		DXConsoleClear();

}

void CDxConsoleSampleNode::OnD3D9FrameRender( float fElapsedTime )
{ 
	DXUTGetD3D9Device()->EndScene();
	DXConsoleRender(DXUTGetD3D9Device(),fElapsedTime);

	DXUTGetD3D9Device()->BeginScene();
}

bool CDxConsoleSampleNode::Unload()
{lua_close(L);
	Singleton<CGame>::Instance()->RemoveMsgProcessorDeposit(this);
	DXConsoleSetActive(false);
	DXConsoleOnLostDevice() ;
	DXConsoleKill();

	return true;
}

bool CDxConsoleSampleNode::Load()
{
	L=lua_open();
	luaL_openlibs(L);
	DXConsoleInitialize(DXUTGetHWNDDeviceWindowed(),DXUTGetD3D9Device(),DXUTGetD3D9BackBufferSurfaceDesc()->Width,DXUTGetD3D9BackBufferSurfaceDesc()->Height);
	DXConsoleOnResetDevice() ;
	DXConsoleSetActive(true);
	DXConsoleSetOnEnterCallback(ConsoleCallbackEnter);
	Singleton<CGame>::Instance()->AddMsgProcessorDeposit(this);
	return true;

}

LRESULT CDxConsoleSampleNode::OnMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam,bool* pbNoFurtherProcessing )
{
	if(DXConsoleIsInit())
	{
		DXConsoleOnInput(uMsg,wParam,lParam);
	}

	return S_OK;
}

